package com.ihr360.feign.interceptor;

import com.ihr360.commons.constant.Constants;
import com.ihr360.commons.context.session.Ihr360Session;
import com.ihr360.commons.context.session.Ihr360SessionContextHolder;
import com.ihr360.commons.entity.AuthUserInfo;
import com.ihr360.commons.lang.StringUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

@Component
public class AuthUserInfoInterceptor implements RequestInterceptor {

    private final static Logger logger = LoggerFactory.getLogger(AuthUserInfoInterceptor.class);

    @Override
    public void apply(RequestTemplate template) {
        Ihr360Session session = Ihr360SessionContextHolder.getSession();
        if (session == null) {
            logger.info("Feign Client Interceptor 无法获取session薪资");
            return;
        }
        AuthUserInfo userInfo = session.getUserInfo();
        if (userInfo == null) {
            logger.info("Feign Client Interceptor 无法获取userInfo薪资");
            return;
        }
        if (!template.headers().containsKey(Constants.Session.COMPANY_ID)) {
            template.header(Constants.Session.COMPANY_ID, userInfo.getCompanyId());
        }
        if (!template.headers().containsKey(Constants.Session.COMPANY_NAME)) {
            String companyName = userInfo.getCompanyName();
            if (StringUtils.isNotEmpty(companyName)){
                template.header(Constants.Session.COMPANY_NAME, Base64Utils.encodeToString(companyName.getBytes()));
            }

        }
        if (!template.headers().containsKey(Constants.Session.IRENSHI_LOCALE_NAME)) {
            //template.header(Constants.Session.IRENSHI_LOCALE_NAME, LocaleContextHolder.getLocale());
        }
        if (!template.headers().containsKey(Constants.Session.MOBILE_NO)) {
            template.header(Constants.Session.MOBILE_NO, userInfo.getMobileNo());
        }
        if (!template.headers().containsKey(Constants.Session.USER_ID)) {
            template.header(Constants.Session.USER_ID, userInfo.getUserId());
        }
        if (!template.headers().containsKey(Constants.Session.USER_NAME)) {
            String userName = userInfo.getUserName();
            if (StringUtils.isNotEmpty(userName)){
                template.header(Constants.Session.USER_NAME, Base64Utils.encodeToString(userName.getBytes()));
            }

        }
    }
}